package day10;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;

public class Demo04 {
    public static void main(String[] args) {
        /*
         * 浅拷贝 与 深拷贝
         */
        User[] arr = {new User(0,"Tom"),
                new User(1,"Jerry"),
                new User(2,"Andy"),
                new User(3,"Wang"),
                new User(4,"Mac")};

        long t1 = System.nanoTime();
        User[] arr2 = Arrays.copyOf(arr, arr.length);
        long t2 = System.nanoTime();

        System.out.println(arr == arr2); //false
        System.out.println(arr[0] == arr2[0]); //true
        arr[0].setName("范");
        System.out.println(arr2[0]);

        long t3 = System.nanoTime();
        User[] arr3 = deepCopy(arr);
        long t4 = System.nanoTime();

        System.out.println(arr == arr3); //false
        System.out.println(arr[0] == arr3[0]); //false

        System.out.println(t2-t1);
        System.out.println(t4-t3);

        //clone 方法也是浅层复制
        //clone 克隆
        User[] arr5 = arr.clone();
        System.out.println(arr == arr5);
        System.out.println(arr[0] == arr5[0]);

        ArrayList<User> list = new ArrayList<>();
        ArrayList<User> list1 = (ArrayList<User>) list.clone();

    }

    /**
     * 利用序列化API实现深层复制
     * @param t 原对象
     * @param <T> 对象类型
     * @return 复制的对象
     */
    public static<T> T deepCopy(T t){
        try {
            ByteArrayOutputStream buf = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(buf);
            //将对象写到内存数组中
            out.writeObject(t);
            out.close();
            //获得对象序列化以后的数据
            byte[] bytes = buf.toByteArray();
            //System.out.println(bytes.length);
            ObjectInputStream in = new ObjectInputStream(
                    new ByteArrayInputStream(bytes));
            //将内存数组反序列化为对象
            T clone = (T)in.readObject();
            in.close();
            return clone;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
class User implements Serializable {
    private int id;
    private String name;

    public User() {
    }

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
